package com.bestv.c2.handler;

import org.apache.commons.lang3.StringUtils;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;

/**
 * Created by Henry on 15/9/2.
 */
public abstract class Handler {
    protected DataSource dataSource;
    protected String outputPath;
    protected File exportFile;
    protected String oracleCharset;

    public abstract void handle() throws IOException, ParseException;

    public String getExportFilePath() {
        return exportFile.getAbsolutePath();
    }

    protected void exportHead(ResultSet rs, Writer out) throws SQLException, IOException {
        ResultSetMetaData metaData = rs.getMetaData();
        int num = metaData.getColumnCount();
        String[] columns = new String[num];

        for (int i=1; i<=num; i++) {
            columns[i-1] = metaData.getColumnName(i);
        }
        out.write(String.format("\"%s\"\n", StringUtils.join(columns, "\",\"")));
    }

    protected void exportData(ResultSet rs, Writer out) throws SQLException, IOException {
        ResultSetMetaData metaData = rs.getMetaData();
        int num = metaData.getColumnCount();
        String[] columns = new String[num];

        while (rs.next()) {
            for (int i=1; i<=num; i++) {
                String field = rs.getString(i);
                columns[i-1] = field == null ? null : new String(field.getBytes(oracleCharset), "GBK");
            }
            out.write(String.format("\"%s\"\n", StringUtils.join(columns, "\",\"")));
        }
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public String getOutputPath() {
        return outputPath;
    }

    public void setOutputPath(String outputPath) {
        this.outputPath = outputPath;
    }

    public File getExportFile() {
        return exportFile;
    }

    public void setExportFile(File exportFile) {
        this.exportFile = exportFile;
    }

    public String getOracleCharset() {
        return oracleCharset;
    }

    public void setOracleCharset(String oracleCharset) {
        this.oracleCharset = oracleCharset;
    }
}
